import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import {
  Card,
  Timeline,
  Button,
  Space,
  Typography,
  Badge,
  Tag,
  Spin,
  Empty,
  Message,
} from '@arco-design/web-react'
import {
  IconLeft,
  IconRefresh,
  IconEye,
} from '@arco-design/web-react/icon'
import { getPipelineById, getPipelineHistory } from '@/api/pipeline'
import type { Pipeline, PipelineInstance } from '@/types'
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
import './index.css'

dayjs.extend(duration)

const { Title, Text, Paragraph } = Typography

// 状态映射
const statusMap: Record<number, { text: string; color: string; status: any }> = {
  0: { text: '等待中', color: 'gray', status: 'default' },
  1: { text: '运行中', color: 'blue', status: 'processing' },
  2: { text: '成功', color: 'green', status: 'success' },
  3: { text: '失败', color: 'red', status: 'error' },
  4: { text: '已取消', color: 'orange', status: 'warning' },
}

export default function PipelineHistory() {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const [loading, setLoading] = useState(true)
  const [pipeline, setPipeline] = useState<Pipeline | null>(null)
  const [history, setHistory] = useState<PipelineInstance[]>([])

  // 加载流水线信息
  const loadPipeline = async () => {
    if (!id) return
    try {
      const data = await getPipelineById(Number(id))
      setPipeline(data)
    } catch (error) {
      console.error('Failed to load pipeline:', error)
      Message.error('加载流水线信息失败')
    }
  }

  // 加载执行历史
  const loadHistory = async () => {
    if (!id) return
    setLoading(true)
    try {
      const data = await getPipelineHistory(Number(id), 50) // 获取最近 50 条
      setHistory(data)
    } catch (error) {
      console.error('Failed to load history:', error)
      Message.error('加载执行历史失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadPipeline()
    loadHistory()
  }, [id])

  // 计算执行时长
  const getDuration = (startTime: string, endTime?: string) => {
    const start = dayjs(startTime)
    const end = endTime ? dayjs(endTime) : dayjs()
    const diff = end.diff(start)
    const dur = dayjs.duration(diff)

    const hours = Math.floor(dur.asHours())
    const minutes = dur.minutes()
    const seconds = dur.seconds()

    if (hours > 0) {
      return `${hours}h ${minutes}m ${seconds}s`
    } else if (minutes > 0) {
      return `${minutes}m ${seconds}s`
    } else {
      return `${seconds}s`
    }
  }

  // 获取状态图标
  const getStatusDot = (status: number) => {
    const config = statusMap[status] || statusMap[0]
    return <Badge status={config.status} />
  }

  if (!pipeline) {
    return (
      <div className="pipeline-history-page">
        <Card loading>
          <div style={{ height: 400 }} />
        </Card>
      </div>
    )
  }

  return (
    <div className="pipeline-history-page">
      <div className="pipeline-history-header">
        <Space>
          <Button
            type="text"
            icon={<IconLeft />}
            onClick={() => navigate('/pipeline')}
          >
            返回
          </Button>
          <Title heading={4} style={{ margin: 0 }}>
            流水线执行历史: {pipeline.name}
          </Title>
        </Space>
        <Button
          type="primary"
          icon={<IconRefresh />}
          onClick={loadHistory}
          loading={loading}
        >
          刷新
        </Button>
      </div>

      <Card>
        {/* 流水线信息 */}
        <div className="pipeline-info">
          <Space size="large">
            <div>
              <Text type="secondary">仓库：</Text>
              <Text>{pipeline.repositoryUrl}</Text>
            </div>
            <div>
              <Text type="secondary">分支：</Text>
              <Tag>{pipeline.branch}</Tag>
            </div>
            <div>
              <Text type="secondary">关联工作流：</Text>
              <Text>{pipeline.workflowDefinition?.name || '-'}</Text>
            </div>
          </Space>
        </div>

        <div className="history-content">
          {loading ? (
            <div style={{ textAlign: 'center', padding: '100px 0' }}>
              <Spin size={40} />
            </div>
          ) : history.length === 0 ? (
            <Empty description="暂无执行历史" />
          ) : (
            <Timeline mode="left">
              {history.map((instance) => {
                const statusConfig = statusMap[instance.status] || statusMap[0]
                return (
                  <Timeline.Item
                    key={instance.id}
                    dot={getStatusDot(instance.status)}
                    label={dayjs(instance.startTime).format('YYYY-MM-DD HH:mm:ss')}
                  >
                    <Card
                      size="small"
                      className="history-item-card"
                      hoverable
                      onClick={() => navigate(`/task/instance/${instance.id}`)}
                    >
                      <Space direction="vertical" style={{ width: '100%' }}>
                        {/* 状态和提交信息 */}
                        <div className="history-item-header">
                          <Badge
                            status={statusConfig.status}
                            text={statusConfig.text}
                            style={{ fontSize: 14, fontWeight: 'bold' }}
                          />
                          <Button
                            type="text"
                            size="mini"
                            icon={<IconEye />}
                            onClick={(e) => {
                              e.stopPropagation()
                              navigate(`/task/instance/${instance.id}`)
                            }}
                          >
                            查看详情
                          </Button>
                        </div>

                        {/* 提交信息 */}
                        <Paragraph style={{ marginBottom: 8 }}>
                          <Text style={{ fontWeight: 'bold' }}>提交信息：</Text>
                          {instance.commitMessage}
                        </Paragraph>

                        {/* 详细信息 */}
                        <Space split="|" size="medium">
                          <div>
                            <Text type="secondary">提交哈希：</Text>
                            <Tag style={{ fontFamily: 'monospace', fontSize: 11 }}>
                              {instance.commitHash?.substring(0, 8)}
                            </Tag>
                          </div>

                          {instance.commitAuthor && (
                            <div>
                              <Text type="secondary">作者：</Text>
                              <Text>{instance.commitAuthor}</Text>
                            </div>
                          )}

                          <div>
                            <Text type="secondary">触发人：</Text>
                            <Text>{instance.triggeredBy}</Text>
                          </div>
                        </Space>

                        {/* 执行时长 */}
                        <div>
                          <Text type="secondary">执行时长：</Text>
                          <Text>
                            {getDuration(instance.startTime, instance.endTime)}
                          </Text>
                        </div>

                        {instance.endTime && (
                          <div>
                            <Text type="secondary">结束时间：</Text>
                            <Text>
                              {dayjs(instance.endTime).format('YYYY-MM-DD HH:mm:ss')}
                            </Text>
                          </div>
                        )}
                      </Space>
                    </Card>
                  </Timeline.Item>
                )
              })}
            </Timeline>
          )}
        </div>
      </Card>
    </div>
  )
}
